<script setup>
import { ref, reactive, getCurrentInstance, onMounted, h } from "vue";
import headerNav from "@/components/headerNav";
import MwDialog from "@/components/Dialog";
import { notifyOpen } from "@/utils/publicFun";
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import AlarmDialog from "@/components/AlarmDialog";
import { goRouter } from "@/utils";
import moment from "moment";
import { globalStore } from "@/store/global";
const globalVue = globalStore();

import config from "./config"

const instance = getCurrentInstance();
const _this = instance.appContext.config.globalProperties //vue3获取当前this
const storage = _this.$utils.storage;

let editPwdShow = ref(false);
let editPwdRef = ref(null);
let editPwdFrom = reactive({})
let editPwdRules = reactive({
  oldPassword: [
    { required: true, message: 'Please input Old Password', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: 'Please input New Password', trigger: 'blur' },
  ],
  newPasswords: [
    { required: true, message: 'Please input Confirm Password', trigger: 'blur' },
  ],
})
let editPwdSubmit = async () => {
  if (editPwdFrom.newPassword != editPwdFrom.newPasswords) {
    ElMessage({
      type: 'error',
      message: 'The two passwords do not match.',
    })
    return 
  }
  let formEl = editPwdRef.value;
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      instance.proxy.$http.put('user.changePassword', editPwdFrom).then(res=>{
        ElMessage({
          type: 'success',
          message: 'Modification succeeded',
        })
        editPwdClose();
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}


let changePassword = () => {
  editPwdShow.value = true;
}
let editPwdClose = () => {
  editPwdShow.value = false;
  for(let item in editPwdFrom){
    if(editPwdFrom[item] instanceof Array){
      editPwdFrom[item] = [];
    }else{
      editPwdFrom[item] = ''
    }
  }
}

let goAccount = () => {
  if (instance != null) {
    _this.$router.push({path: '/account', query: {}})
  }
}

let onExit = () => {
  ElMessageBox.confirm(
    'Exit or not ？',
    'Exit',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel'
    }
  )
    .then(() => {
      storage.clearAll();
      _this.$router.push({path: '/login', query: {}})
      ElMessage({
        type: 'success',
        message: 'Exit successfully',
      })
    })
    .catch(() => {})
}

let state = reactive({
  title: config.title,
  menu: config.menu,
  infoNum: 0,
  userName: 'Roboto',
  userMenu: [
    { label: 'Change Password', onClick: changePassword},
    { label: 'Exit', onClick: onExit},
  ]
})
const stateList = ref([])

let userInfo = JSON.parse(storage.getLocal('userinfo'));
  
onMounted(() => {
  if(userInfo) {
    init();
    onWebsocket();
    state.userName = userInfo.username || '';
  }else{
    goRouter('/login');
  };
});

let init = () => {
  if (userInfo?.role == 0) {
    state.userMenu.splice(1,0,{label: 'Account ', onClick: goAccount});
  } ;
  instance.proxy.$http.get('user.getAlarmUntreatedNum').then(res=>{
    state.infoNum = res.data.num || 0;
    globalVue.setAlarmNumber(res.data.num || 0);
  });
  getSelectList();
};

// 获取甘特图状态数据
let getSelectList = () => {
  instance.proxy.$http.get('archiveData.dictDetail', {params: {name: 'alarm_type_status'}}).then(res=>{
		stateList.value = res.data.map(i => {
			if (i.value == 'PHONE') {
				i['stateName'] = 'Phone';
				i['backgroundColor'] = 'rgba(251, 57, 60, 1)'
				i['icon'] = require("@/assets/image/index/list_ico_phone.png")
			}
			if (i.value == 'YAWN') {
				i['stateName'] = 'Yawn';
				i['backgroundColor'] = 'rgba(58, 78, 252, 1)'
				i['icon'] = require("@/assets/image/index/list_ico_sleepy.png")
			}
			if (i.value == 'SMOKE') {
				i['stateName'] = 'Smoke';
				i['backgroundColor'] = 'rgba(253, 144, 38, 1)'
				i['icon'] = require("@/assets/image/index/list_ico_somke.png")
			}
			return i;
		})
  })
};

let openAlarm = () => {
  let params = {
		// startTime: moment().format("YYYY-MM-DD") + ' 00:00:00',
		// endTime: moment().format("YYYY-MM-DD") + ' 23:59:59',
  };
  instance.proxy.$http.get('user.getAlarmPushList',{params}).then(res=>{
    let list = res.data.map(item => {
      let statusObj = stateList.value.find(j => !j.label.indexOf(item.alarmTypeName));
      let obj = {...item, ...statusObj};
      return obj;
    })
    notifyOpen(list);
  });
}

let handleAlarmSubmit = (form) => {
	return new Promise(function (resolve, reject) {
    if (!form.handleContent) {
      ElMessage({
        type: 'error',
        message: 'Please Enter Handling Content',
      });
      reject('Please Enter Handling Content');
      return;
    };
    let userInfo = JSON.parse(storage.getLocal('userinfo'));
    form['userId'] = userInfo.userId;
    form['username'] = userInfo.username;
		instance.proxy.$http.post('archiveData.handleAlarm', form).then(res=>{
			resolve(res);
		}).catch(err => reject(err));
	});
};

let onWebsocket = () => {
  // WebSocket构造函数，创建WebSocket对象 
  let ws = new WebSocket(process.env.NODE_ENV === 'production' ? window.global_API.webSocketProdUrl : window.global_API.webSocketDevUrl)

  // 连接成功后的回调函数
  ws.onopen = function (params) {
    console.log(process.env.NODE_ENV === 'production' ? window.global_API.webSocketProdUrl : window.global_API.webSocketDevUrl)
    console.log('客户端连接成功')
    // 向服务器发送消息
    ws.send('hello')
  };

  // 从服务器接受到信息时的回调函数
  ws.onmessage = function (e) {
    let data = JSON.parse(e.data);
    console.log('收到服务器响应', data)
    if (data instanceof Array) {
      let list = data.map(item => {
        let statusObj = stateList.value.find(j => !j.label.indexOf(item.alarmTypeName));
        let obj = {...item, ...statusObj};
        return obj;
      })
      notifyOpen(list);
    }else{
      if(/\d/g.test(data.num)){
        state.infoNum = data.num;
        globalVue.setAlarmNumber(data.num);
      }else{
        let statusObj = stateList.value.find(j => !j.label.indexOf(data.alarmTypeName));
        let obj = {...data, ...statusObj};
        notifyOpen(obj);
      }
    }
  };

  // 连接关闭后的回调函数
  ws.onclose = function(evt) {
    console.log("关闭客户端连接");
  };

  // 连接失败后的回调函数
  ws.onerror = function (evt) {
    console.log("连接失败了");
  };


  // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，这样服务端会抛异常。
  window.onbeforeunload = function() {
    ws.close();
  }  
}
</script>
<template>
  <el-container class="container">
    <el-header class="heaader">
      <headerNav
        :menu="state.menu" 
        :projectTitle="state.title"
        :infoNum="state.infoNum"
        :userName="state.userName"
        :userMenu="state.userMenu"
        @openAlarm="openAlarm"
      ></headerNav>
    </el-header>
    <el-main class="main">
      <router-view></router-view>
    </el-main>
  </el-container>

  <mw-dialog
    :show="editPwdShow"
    title="Change Password"
    @submit="editPwdSubmit"
    @close="editPwdClose"
  >
    <el-form ref="editPwdRef" :model="editPwdFrom" label-width="140px" :rules="editPwdRules">
      <el-form-item label="Old Password" prop="oldPassword">
        <el-input v-model="editPwdFrom.oldPassword" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="New Password" prop="newPassword">
        <el-input type="password" v-model="editPwdFrom.newPassword" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Confirm Password" prop="newPasswords">
        <el-input type="password" v-model="editPwdFrom.newPasswords" placeholder="Enter" clearable />
      </el-form-item>
    </el-form>
  </mw-dialog>
</template>
<style lang="less" scoped>
.container{
  height: 100%;
  width: 100%;
  .heaader{
    padding: 0;
    width: 100%;
    z-index: 20;
    background-color: var(--mw-page-background-bright-color);
    box-shadow: 0px 6px 12px 1px rgba(58,140,252,0.2);
  }
  .main{
    z-index: 10;
    background-color: var(--mw-page-background-color);
    padding: 0;
  }
}
</style>